package com.zsl.controller.Admin;

import com.alibaba.fastjson.JSON;
import com.zsl.service.CategoryService;
import com.zsl.service.impl.CategoryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "OpCategory",urlPatterns = "/op/category")
public class OpCategory extends HttpServlet {
    CategoryService categoryService=new CategoryServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Map<String, Object> res = new HashMap<>();

        //获取数据
        String service=request.getParameter("service").equals("")?null:request.getParameter("service");
        if(service==null){
            res.put("code",0);
            res.put("line",0);
            res.put("msg","未知错误");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(res));
            return;
        }
        //插入一个分类信息
        if(service.equals("insert")){
            String c_name=request.getParameter("c_name").equals("")?null:request.getParameter("c_name");
            String c_description=request.getParameter("service").equals("")?null:request.getParameter("c_description");
            try {
                res=categoryService.insertCategory(c_name,c_description);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                res.put("code",0);
                res.put("line",0);
                res.put("msg","未知错误");
            }finally {
                PrintWriter out = response.getWriter();
                out.write(JSON.toJSONString(res));
            }
        }
        //TODO 更新一个分类信息(前端功能未完成)
        else if (service.equals("也有可能是update")){
            String c_name=request.getParameter("c_name").equals("")?null:request.getParameter("c_name");
            String c_description=request.getParameter("service").equals("")?null:request.getParameter("c_description");
            res.put("code",0);
            res.put("line",0);
            res.put("msg","功能未完成");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(res));
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
